# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

from absl import app, flags

import pandas
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import datetime

FLAGS = flags.FLAGS


def plot_histogram(funding_rate_df):
  plt.figure(figsize=(10, 10))
  plt.title('histogram of Bitmex funding rate history')
  plt.hist(funding_rate_df['fundingRate'], bins=50)
  plt.yscale('log', basey=2)
  plt.savefig('hist/hist_funding_rate.png')


def simple_stats_and_print(funding_rate_df):
  percentiles = [.1, .2, .3, .4, .5, .6, .7, .8, .9, .99]
  print(funding_rate_df['fundingRate'].describe(percentiles=percentiles))


# Get rid of data before 2017.
def filter_out_old_date(funding_rate_df):
  funding_rate_df['timestamp'] = pandas.to_datetime(funding_rate_df['timestamp'])
  funding_rate_df = funding_rate_df.loc[
      funding_rate_df['timestamp'] > datetime.datetime(2017, 1, 1)]
  return funding_rate_df


def read_csv_into_df(csv_path):
  df = pandas.read_csv(csv_path, sep=',', header=0)
  return df


def main(argv):
  csv_path = FLAGS.csv_path
  assert csv_path, '--csv_path must be specified.'

  funding_rate_df = read_csv_into_df(csv_path)
  funding_rate_df = filter_out_old_date(funding_rate_df)
  simple_stats_and_print(funding_rate_df)
  plot_histogram(funding_rate_df)

  return 0


if __name__ == '__main__':
  flags.DEFINE_string('csv_path', None, 'Intput csv file path.')

  app.run(main)
